const Controller = require('egg').Controller
const isJSON = require('koa-is-json');
// const createRule = {
//   username: {
//     type: 'email'
//   },
//   password: {
//     type: 'passowrd',
//     compare: 're-password'
//   }
// }
const createRule = {
  username: {
    type: 'email',
  },
  password: {
    type: 'password',
    compare: 're-password',
  },
};

class UserController extends Controller {
  async index() {
    const { params} = this.ctx
    this.ctx.body = `参数命名方式访问: id: ${params.id}, name: ${params.name}`
  }
  async regexp () {
    const {params} = this.ctx
    this.ctx.body = `package params: ${params[0]}`
  }
  async post () {
    this.ctx.body = `form data: ${JSON.stringify(this.ctx.request.body)}`
  }
  /**
   * 表单校验
   * // curl -X POST http://127.0.0.1:7001/user --data 'username=abc@abc.com&password=111111&re-password=111111'
   */
  async create () {
    const {ctx} = this
    let validateMsg;
    try {
      ctx.validate(createRule);
    } catch (err){
      validateMsg = err || err.message;
    }
    if (validateMsg) {
      ctx.body = isJSON(validateMsg) ? JSON.stringify(validateMsg) : validateMsg;
    } else {
      ctx.body = `form submit success!`;
    }
  }
}

module.exports = UserController